<!--
 * @Description: 选择区域
 * @Author: qingyang
 * @Date: 2024-01-18 17:32:05
 * @LastEditors: qingyang
 * @LastEditTime: 2024-01-18 17:32:05
-->
<template>
  <el-cascader
    ref="casRef"
    :options="options"
    class="c-select-area"
    v-model="localValue"
    :placeholder="placeholder"
    :props="casProps"
    :clearable="props.clearable"
    @change="handleChange"
    @visible-change="handleVisibleChange"
    filterable
  >
  </el-cascader>
</template>
<script lang="ts">
export default {
  name: 'FieldSelect'
};
</script>
<script lang="ts" setup>
import { defineProps, withDefaults, defineEmits, computed, ref } from 'vue';
import type { CascaderProps } from 'element-plus';
import { getDictTypeList, getDictByType } from '@/apis/system/dataDict';

interface CSelectProps {
  value: string[] | string;
  clearable?: boolean;
  placeholder?: string;
}
const props = withDefaults(defineProps<CSelectProps>(), {
  clearable: true,
  placeholder: '请选择'
});
const options = ref([]);

const casRef = ref();
const casProps: CascaderProps = {
  lazy: true,
  lazyLoad(node, resolve) {
    const { level, value, pathLabels } = node;
    console.log('node', node);
    if (level == 0) {
      getDictTypeList().then(res => {
        const nodes = res.map(item => ({
          value: `${item.dataGroup}-${item.dataType}`,
          label: item.dataDesc,
          leaf: false
        }));

        resolve(nodes);
      });
    } else {
      getDictByType(value.split('-')[0], value.split('-')[1]).then(res => {
        const nodes = res.map(item => ({
          value: item.dataCode,
          label: item.dataValue,
          leaf: true
        }));
        resolve(nodes);
      });
    }
  }
};

const emit = defineEmits(['update:value', 'change']);

const localValue = computed({
  get: () => {
    return props.value;
  },
  set: val => {
    emit('update:value', val);
  }
});

const handleChange = (value: string, params: any) => {
  const data = casRef.value.getCheckedNodes();
  if (data && data.length) {
    console.log('change', data[0].value);
    emit('change', data[0].value);
  } else {
    emit('change', []);
  }
};
const handleVisibleChange = (val: boolean) => {
  options.value = [];
};
</script>

<style lang="scss">
.c-select-area {
  width: 100%;
  .el-input__wrapper {
    height: 32px;
  }
}
</style>
